/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import React, { memo, useCallback, useMemo, useRef } from 'react';
import { LayoutChangeEvent, StatusBar, StyleProp, View, ViewStyle } from 'react-native';
import { WINDOW_HEIGHT } from '../../constants';
import { print } from '../../utilities';
import { styles } from './styles';
import type { AdaptiveSheetContainerProps } from './types';

function AdaptiveSheetContainerComponent({
  containerHeight,
  containerOffset,
  topInset = 0,
  bottomInset = 0,
  shouldCalculateHeight = true,
  detached,
  style,
  children,
}: AdaptiveSheetContainerProps): JSX.Element {
  const containerRef = useRef<View>(null);
  const containerStyle = useMemo<StyleProp<ViewStyle>>(
    () => [
      style,
      styles.container,
      {
        paddingTop: topInset,
        paddingBottom: bottomInset,
        overflow: detached ? 'visible' : 'hidden',
      },
    ],
    [style, detached, topInset, bottomInset],
  );

  const handleContainerLayout = useCallback(
    function handleContainerLayout({
      nativeEvent: {
        layout: { height },
      },
    }: LayoutChangeEvent) {
      containerHeight.value = height;

      containerRef.current?.measure((_x, _y, _width, _height, _pageX, pageY) => {
        if (!containerOffset.value) {
          return;
        }
        containerOffset.value = {
          top: pageY ?? 0,
          left: 0,
          right: 0,
          bottom: Math.max(0, WINDOW_HEIGHT - ((pageY ?? 0) + height + (StatusBar.currentHeight ?? 0))),
        };
      });

      print({
        component: AdaptiveSheetContainer.displayName,
        method: 'handleContainerLayout',
        params: {
          height,
        },
      });
    },
    [containerHeight, containerOffset, containerRef],
  );

  return (
    <View
      ref={containerRef}
      pointerEvents="box-none"
      onLayout={shouldCalculateHeight ? handleContainerLayout : undefined}
      style={containerStyle}
      children={children}
    />
  );
}

const AdaptiveSheetContainer = memo(AdaptiveSheetContainerComponent);
AdaptiveSheetContainer.displayName = 'AdaptiveSheetContainer';

export default AdaptiveSheetContainer;
